using System;
using MvpFramework.Infastructure;
using StructureMap;

namespace MvpFramework
{
    /// <summary>
    /// Factory that creates Presenters for views
    /// </summary>
    public class PresenterFactory
    {
        private readonly IViewPresenterResolver _defaultResolver;
   

        /// <summary>
        /// Uses Naming Stategy to resolve presenters to views
        /// </summary>
        public PresenterFactory()
            : this(new GenericTypeResolver())
        {
        }

        public PresenterFactory(IViewPresenterResolver defaultResolver)
        {
            _defaultResolver = defaultResolver;
        }

        /// <summary>
        /// Returns an instance of the proper presenter for the view sent
        /// </summary>
        /// <param name="view">instance of the View to get the presenter for</param>
        /// <returns>A presenter for the view</returns>
        public object GetPresenterFor<T>(T view) 
            where T:IMvpView
        {
            if(view == null)
            {
                throw new Exception(String.Format("Can not get presenter for {0}. It does not implment IMvpView",view.GetType()));
            }
            var presenter = _defaultResolver.GetPresenterTypeFor(view);

            return ObjectFactory.With("view").EqualTo(view).GetInstance(presenter);
        }
    }
}